package com.zweirm.lagee_quizing.service;

import com.zweirm.lagee_quizing.domain.Clazz;
import com.zweirm.lagee_quizing.domain.Paper;
import com.zweirm.lagee_quizing.domain.Quiz;
import com.zweirm.lagee_quizing.repository.ClazzRepository;
import com.zweirm.lagee_quizing.repository.PaperRepository;
import com.zweirm.lagee_quizing.repository.QuizRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class QuizService {
    @Autowired
    private PaperRepository paperRepository;

    @Autowired
    private QuizRepository quizRepository;

    @Autowired
    private ClazzRepository clazzRepository;

    public List<Quiz> findAllQuiz(String status) {
        return quizRepository.findAllByStatus(status);
    }

    public void saveQuiz(String title, String type, String[] clazz, String paper) {
        Quiz quiz = new Quiz();
        quiz.setStatus("1");
        quiz.setTitle(title);
        quiz.setType(type);

        List<Clazz> clazzesList = new ArrayList<>();
        for (String clazzStr : clazz) {
            Clazz destClazz = clazzRepository.findClazzByName(clazzStr);
            clazzesList.add(destClazz);
            clazzRepository.save(destClazz);
        }
        quiz.setClazzes(clazzesList);

        Paper destPaper = paperRepository.findPaperByName(paper);
        quiz.setPaper(destPaper);

        quizRepository.save(quiz);
    }

    public Quiz quizDetails(Long quizId) {
        return quizRepository.findQuizById(quizId);
    }

    public void quizUpdate(String title,
                           String type,
                           String[] clazz,
                           String paper,
                           Long quizId) {
        Quiz quiz = quizRepository.findQuizById(quizId);
        quiz.setTitle(title);
        quiz.setType(type);

        List<Clazz> clazzesList = new ArrayList<>();
        for (String clazzStr : clazz) {
            Clazz destClazz = clazzRepository.findClazzByName(clazzStr);
            clazzesList.add(destClazz);
            clazzRepository.save(destClazz);
        }
        quiz.setClazzes(clazzesList);

        Paper destPaper = paperRepository.findPaperByName(paper);
        quiz.setPaper(destPaper);

        quizRepository.save(quiz);
    }

    public void deleteQuiz(Long quizId) {
        Quiz quiz = quizRepository.findQuizById(quizId);
        quiz.setStatus("0");
        quizRepository.save(quiz);
    }

    public Quiz findQuizById(Long quizId) {
        return quizRepository.findQuizById(quizId);
    }
}
